﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Media;
using System.Threading;
using Twitterizer.Framework;

namespace httpSentry
{
    public partial class Form1 : Form
    {
        string[] Names = new string[] {
            "userName", 
            "Password", 
            "url2Check", 
            "urlContains", 
            "secondsBetween", 
            "failuresBeforeReporting"
        };
        
        Dictionary <string,string> configValues;
        int _failureCount = 0;
        //int _maxFailures = 1;
        string upWAV = Application.StartupPath + "\\up.wav";
        string downWAV = Application.StartupPath + "\\Down.wav";
        Twitter _twit; 


        public Form1()
        {
            InitializeComponent();

            configValues = XMLConfiguration.Load(Application.UserAppDataPath, Names);
            if (configValues != null)
            {
                userName.Text = configValues.ContainsKey("userName") ? configValues["userName"] : string.Empty;
                Password.Text = configValues.ContainsKey("Password") ? configValues["Password"] : string.Empty;
                url2Check.Text = configValues.ContainsKey("url2Check") ? configValues["url2Check"] : string.Empty;
                urlContains.Text = configValues.ContainsKey("urlContains") ? configValues["urlContains"] : string.Empty;
                secondsBetween.Text = configValues.ContainsKey("secondsBetween") ? configValues["secondsBetween"] : string.Empty;
                failuresBeforeReporting.Text = configValues.ContainsKey("failuresBeforeReporting") ? configValues["failuresBeforeReporting"] : string.Empty;
            }
            if ((!String.IsNullOrEmpty(userName.Text)) && (!String.IsNullOrEmpty(Password.Text)))
            {
                _twit = new Twitter(userName.Text, Password.Text);
            }
            openFileDialog1.InitialDirectory = Application.StartupPath;
        }

        private void tock()
        {
            AppendText(messages, Color.Blue, "*** Checking " + DateTime.Now.ToString() + " \n");
            string rawBack = "";
            try
            {
                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("{0}", url2Check.Text));
                WebReq.Method = "GET";
                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                rawBack = _Answer.ReadToEnd();

            }
            catch { }
            
            if (rawBack.Contains(urlContains.Text))
            {
                _failureCount = 0;
                AppendText(messages, Color.Blue, "response Contains " + urlContains.Text + "\n");

                if (checkBox2.Checked)
                {
                    SoundPlayer spUp = new SoundPlayer(upWAV);
                    spUp.Play();
                }
            }
            else
            {
                _failureCount++;
                if (_failureCount >= int.Parse(failuresBeforeReporting.Text))
                {
                    AppendText(messages, Color.Red, "****** Site Down !!! ******" + DateTime.Now.ToString() + " \n");
                    SoundPlayer sp = new SoundPlayer(downWAV);
                    sp.Play();
                    _twit.Status.Update("*Down Alert - [" + url2Check.Text + "]");
                    _failureCount = 0;
                }
                
            }

            if (!timer1.Enabled)
            {
                timer1.Interval = (Convert.ToInt32(secondsBetween.Text) * 1000);
                timer1.Enabled = true;
            }
            else
            {
                if (checkBox1.Checked)
                {
                    timer1.Enabled = false;
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            AppendText(messages, Color.Black, "*** Starting "+DateTime.Now.ToString()+" \n");
            this.Text = "httpSentry " + url2Check.Text;
            tock();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //AppendText(richTextBox1, Color.Black, "*** Tick \n");
            tock();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            AppendText(messages, Color.Black, "*** Stopping " + DateTime.Now.ToString() + " \n");
            this.Text = "httpSentry Stopped";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Sound Files|*.wav";
            openFileDialog1.Title = "Select a Sound File";
            
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox4.Text = openFileDialog1.SafeFileName;
                downWAV = openFileDialog1.FileName;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SoundPlayer sp = new SoundPlayer(downWAV);
            sp.Play();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SoundPlayer sp = new SoundPlayer(upWAV);
            sp.Play();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Sound Files|*.wav";
            openFileDialog1.Title = "Select a Sound File";
            

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox5.Text = openFileDialog1.SafeFileName;
                upWAV = openFileDialog1.FileName;
            }

        }

        private void button7_Click(object sender, EventArgs e)
        {
            messages.Text = "";
        }
        // Append text of the given color.
        void AppendText(RichTextBox box, Color color, string text)
        {
            int start = box.TextLength;
            box.AppendText(text);
            int end = box.TextLength;

            // Textbox may transform chars, so (end-start) != text.Length
            box.Select(start, end - start);
            {
                box.SelectionColor = color;
                // could set box.SelectionBackColor, box.SelectionFont too.
            }
            box.SelectionLength = 0; // clear
        }

        private void button8_Click(object sender, EventArgs e)
        {
            configValues = new Dictionary<string, string>();
            configValues.Add("userName", userName.Text);
            configValues.Add("Password", Password.Text);
            configValues.Add("url2Check", url2Check.Text);
            configValues.Add("urlContains", urlContains.Text);
            configValues.Add("secondsBetween", secondsBetween.Text);
            configValues.Add("failuresBeforeReporting", failuresBeforeReporting.Text);
            XMLConfiguration.Save(Application.UserAppDataPath, configValues);

        }

        private void button9_Click(object sender, EventArgs e)
        {
            configValues = XMLConfiguration.Load(Application.UserAppDataPath, Names);
            if (configValues != null)
            {
                userName.Text = configValues.ContainsKey("userName") ? configValues["userName"] : string.Empty;
                Password.Text = configValues.ContainsKey("Password") ? configValues["Password"] : string.Empty;
                url2Check.Text = configValues.ContainsKey("url2Check") ? configValues["url2Check"] : string.Empty;
                urlContains.Text = configValues.ContainsKey("urlContains") ? configValues["urlContains"] : string.Empty;
                secondsBetween.Text = configValues.ContainsKey("secondsBetween") ? configValues["secondsBetween"] : string.Empty;
                failuresBeforeReporting.Text = configValues.ContainsKey("failuresBeforeReporting") ? configValues["failuresBeforeReporting"] : string.Empty;
            }
            if ((!String.IsNullOrEmpty(userName.Text)) && (!String.IsNullOrEmpty(Password.Text)))
            {
                _twit = new Twitter(userName.Text, Password.Text);
            }

        }

    }
}
